import React, { useState, useEffect, useRef } from 'react';
import styles from '../../css/home.module.css';
import AMapLoader from '@amap/amap-jsapi-loader';
import { getStrategyData } from '../../api/api';
import { fetchScenicData } from '../../api/scenicData';

// 图片导入
import wetherImg from '../../assets/weather.png';
import block1Img from '../../assets/ticket.png';
import block2Img from '../../assets/call.png';
import search from '../../assets/search.png';
import hourse2 from '../../assets/hourse2.png';
import flower from '../../assets/flower.png';
import send from '../../assets/send.png';
import tree from '../../assets/tree.png';
import mines from '../../assets/mine.png';
import map from '../../assets/map.png';
import use from '../../assets/use.png';
import show from '../../assets/show.png';
import notice from '../../assets/notice.png';
import game from '../../assets/game.png';
import active from '../../assets/active.png';
import ranking from '../../assets/ranking.png';
import fire from '../../assets/fire.png';
import errorImg from '../../assets/error.png';

import { imgUrl } from '../../config';

import { useNavigate } from 'react-router-dom';

const FirstPage = () => {
    const navigate = useNavigate();
    const [data, setData] = useState([]);
    const [jingData, setJingData] = useState([]);
    const [strategyData, setStrategyData] = useState([]);
    const [weatherInfo, setWeatherInfo] = useState({
        province: '',
        city: '定位中...',
        humidity: '空气湿度：--',
        forecast: '加载中...'
    });
    const isMounted = useRef(true);
    const imgRef = useRef(null);

    // 获取当前位置
    const getCurrentLocation = () => {
        return new Promise((resolve, reject) => {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        resolve({
                            longitude: position.coords.longitude,
                            latitude: position.coords.latitude
                        });
                    },
                    (error) => {
                        console.error('获取位置失败:', error);
                        reject(error);
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 5000,
                        maximumAge: 0
                    }
                );
            } else {
                reject(new Error('浏览器不支持地理位置功能'));
            }
        });
    };

    // 格式化日期函数
    const formatDate = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        
        // 获取星期几
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const weekday = weekdays[date.getDay()];
        
        return `${year}-${month}-${day} ${weekday}`;
    };

    // 初始化地图和天气
    const initMapAndWeather = async () => {
        try {
            const AMap = await AMapLoader.load({
                key: "fedff415d7e466acaf5ab7399c91f830",
                version: "1.4.15",
                plugins: ['AMap.Weather', 'AMap.CitySearch'],
                securityJsCode: "f6c34b219f0642ab1ed5553d662b7cfe"
            });

            // 获取当前位置
            const position = await getCurrentLocation();
            
            // 根据坐标获取城市名称
            const city = await new Promise((resolve, reject) => {
                AMap.plugin('AMap.CitySearch', () => {
                    const citySearch = new AMap.CitySearch();
                    citySearch.getLocalCity((status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            resolve(result.city.replace('市', '')); // 去掉"市"字
                        } else {
                            reject(new Error('获取城市信息失败'));
                        }
                    });
                });
            });

            // 更新城市信息
            setWeatherInfo(prev => ({
                ...prev,
                city: city || '新乡'
            }));

            // 创建地图实例
            new AMap.Map('container', {
                resizeEnable: true,
                center: [position.longitude, position.latitude],
                zoom: 12
            });

            // 获取天气信息
            AMap.plugin('AMap.Weather', () => {
                const weather = new AMap.Weather();
                
                // 获取实时天气
                weather.getLive(city, (err, data) => {
                    if (err || !isMounted.current) return;
                    setWeatherInfo(prev => ({
                        ...prev,
                        province: data.province,
                        city: data.city,
                        humidity: `空气湿度：${data.humidity}`
                    }));
                });

                // 获取天气预报
                weather.getForecast(city, (err, data) => {
                    if (err || !data.forecasts.length || !isMounted.current) return;
                    
                    // 获取今天的预报
                    const todayForecast = data.forecasts[0];
                    
                    // 格式化日期
                    const formattedDate = formatDate(todayForecast.date);
                    
                    // 构建完整的天气信息
                    const forecast = `${formattedDate} <span class="weather">${todayForecast.dayWeather}</span> ${todayForecast.nightTemp}~${todayForecast.dayTemp}℃`;
                    
                    setWeatherInfo(prev => ({ ...prev, forecast }));
                });
            });

        } catch (error) {
            console.error('初始化地图或天气失败:', error);
            // 使用默认城市北京作为回退
            setWeatherInfo(prev => ({
                ...prev,
                city: '新乡',
                humidity: '空气湿度：--'
            }));
        }
    };

    useEffect(() => {
        initMapAndWeather();
        
        // 获取景区数据
        fetchScenicData()
            .then((res) => {
                if (res?.data) {
                    setData(res.data);
                    setJingData(res.data);
                    sessionStorage.setItem("jingqu", JSON.stringify(res.data));
                }
            })
            .catch(console.error);

        // 获取攻略数据
        getStrategyData()
            .then((res) => {
                if (res?.data) setStrategyData(res.data);
            })
            .catch(console.error);

        return () => {
            isMounted.current = false;
        };
    }, []);

    // 图片加载错误处理函数
    const handleImageError = (e) => {
        e.target.src = errorImg;
    };

    // 跳转到景区详情页
    const goToDetail = (id, index) => {
        sessionStorage.setItem("jingid", id);
        sessionStorage.setItem("jingdata", JSON.stringify(jingData[index]));
        navigate("/scenicdetails");
    };

    // 跳转到攻略详情页
    const goToStrategyDetail = (i, id) => {
        const selectedStrategy = strategyData[i];
        if (selectedStrategy) {
            sessionStorage.setItem("game", JSON.stringify(selectedStrategy));
            sessionStorage.setItem("gameimg", selectedStrategy.img || "");
            navigate("/strategy");
        } else {
            console.error("未找到对应的攻略数据");
        }
    };

    // 跳转到发布页面并添加动画
    const goToPublish = () => {
        const img = imgRef.current;
        if (img) {
            img.style.marginTop = '-2000px';
            img.style.transition = 'all 2s';
            setTimeout(() => {
                navigate("/issue");
            }, 2000);
        }
    };

    const handleClick = () => {
        sessionStorage.setItem('jingid', '3');
        sessionStorage.setItem('video', 'video');
        sessionStorage.setItem('img', 'img');
        navigate("/tickets");
    };

    const maps = () => {
        navigate("/map");
    };

    const goactive = () => {
        navigate("/active");
    };

    const games = () => {
        navigate("/game");
    };

    const goplay = () => {
        navigate("/ranking");
    };

    return (
        <div style={{ marginBottom: '10px', backgroundColor: '#F0F8FF' }}>
            <div className={styles.info} style={{ display: 'none' }}>
                <p id='forecast'></p>
            </div>
            <div className={styles.big}>
                <div className={styles.imagebig}>
                    <div className={styles.image}></div>
                    <div className={styles.top}>
                        <div className={styles.sky}>
                            <img src={wetherImg} alt="天气图标" />
                            <p id="wether" dangerouslySetInnerHTML={{ __html: weatherInfo.forecast }}></p>
                        </div>
                        <div className={styles.font}>
                            <span className={styles.wind}>{weatherInfo.humidity}</span>
                            <br />
                            <b className={styles.address}>{weatherInfo.city}</b><br />
                        </div>
                        <div className={styles.border} onClick={() => navigate("/search")}>
                            <img src={search} alt="搜索" />
                            <p>搜索</p>
                        </div>
                    </div>
                    <div className={styles.fif}>
                        <div className={styles['one-block']} onClick={handleClick}>
                            <img src={block1Img} alt="售票专区" />
                            <p>售票专区</p>
                        </div>
                        <div className={styles['one-block']}>
                            <img src={block2Img} alt="景点讲解" />
                            <p>景点讲解</p>
                        </div>
                        <div className={styles['one-block']} onClick={maps}>
                            <img src={map} alt="景区地图" />
                            <p>景区地图</p>
                        </div>
                        <div className={styles['one-block']} onClick={() => navigate("/intruduce")}>
                            <img src={use} alt="景区地图" />
                            <p>使用说明</p>
                        </div>
                        <div className={styles['one-block']} onClick={() => navigate("/perform")}>
                            <img src={show} alt="景区地图" />
                            <p>演出预告</p>
                        </div>
                    </div>
                    <div className={styles.notice}>
                        <img src={notice} alt="" />
                        <p>这里是公告</p>
                    </div>
                </div>
                <div className={styles.bto}>
                    <div className={styles.threeblck}>
                        <img onClick={games} src={game} alt="" />
                        <div className={styles.twoblock}>
                            <img onClick={goactive} src={active} alt="" />
                            <img onClick={goplay} src={ranking} alt="" />
                        </div>
                    </div>
                </div>
                <div className={styles.recommend}>
                    <div>
                        <img id={styles.rem} src={fire} alt="" />
                        <p>推荐景区</p>
                    </div>
                    <div
                        className={styles['more-btn']}
                        style={{ width: '45px', backgroundColor: '#ffffff', borderRadius: '20px', marginRight: '10px', margin: '0 5px', padding: '1px 3px', textAlign: 'center' }}
                        onClick={() => navigate("/ranking")}
                    >
                        <p>更多</p>
                    </div>
                </div>
                <div className={styles.maxproduct}>
                    {data.map((item, index) => (
                        <div key={item.id} className={styles.product} onClick={() => goToDetail(item.id, index)}>
                            <img 
                               src={`${imgUrl}${item.img}`} 
                                alt={item.label} 
                                onError={handleImageError}
                            />
                            <p>{item.label}</p>
                            <div className={styles.content}>
                                <div className={styles.contentone}>
                                    <span style={{ marginRight: '0px' }}>{item.score}分</span>
                                    <div className={styles.line}></div>
                                    <span style={{ marginLeft: '0px' }}>评价5</span>
                                </div>
                                <div className={styles.discuss}>
                                    <span>{item.num == null ? "0" : item.num > 999 ? item.num + "+" : item.num}</span>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
                <div className={styles.strategy}>
                    <div>
                        <img id={styles.rem} src={fire} alt="" />
                        <p>推荐攻略</p>
                    </div>
                    <div
                        className={styles.morebtn}
                        style={{ width: '45px', backgroundColor: '#ffffff', borderRadius: '20px', marginRight: '10px', margin: '0 5px', textAlign: 'center' }}
                        onClick={() => navigate("/game")}
                    >
                        <p>更多</p>
                    </div>
                </div>
                <div className={styles.maxstrategy}>
                    {strategyData.map((item, index) => (
                        <div key={item.id} className={styles.strategys} onClick={() => goToStrategyDetail(index, item.id)}>
                            <img 
                               src={`${imgUrl}${item.img}`} 
                                alt={item.title} 
                                onError={handleImageError} 
                            />
                            <p>{item.title}</p>
                            <div className={styles['strategy-content']}>
                                <div className={styles['strategy-one']}>
                                    <img
                                        src={`${imgUrl}${item.avatar}`}
                                        alt={item.name}
                                        onError={handleImageError}
                                    />
                                    <span>{item.name}</span>
                                </div>
                                <div className={styles['strategyImg']}>
                                    <span>{item.like_num > 999 ? item.like_num + "+" : item.like_num == null ? 0 : item.like_num}</span>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', marginTop: '20px', color: '#4b4b4b', marginBottom: '16vh' }}>
                    <span style={{ fontSize: '14px', textAlign: 'center' }}>没有更多了...</span>
                </div>
                <div className={styles.bottom}>
                    <div className={styles.second}>
                        <img src={hourse2} alt="" />
                        <p>首页</p>
                    </div>
                    <div className={styles.first} onClick={() => navigate("/game")}>
                        <img src={flower} alt="" />
                        <p>攻略</p>
                    </div>
                    <div className={styles.plane} onClick={goToPublish}>
                        <div className={styles.aircraft}>
                            <img ref={imgRef} src={send} alt="" />
                        </div>
                        <p style={{ marginTop: '33px', textAlign: 'center' }}>发布</p>
                    </div>
                    <div className={styles.first} onClick={() => navigate("/ranking")}>
                        <img src={tree} alt="" />
                        <p>排行榜</p>
                    </div>
                    <div className={styles.first} onClick={() => navigate("/mine")}>
                        <img src={mines} alt="" />
                        <p>我的</p>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default FirstPage;